<template>
    <div v-loading="formLoading">
        <el-tree :data="records" ref="tree" :props="defaultProps" show-checkbox node-key="id"
            :default-checked-keys="defaultCheckedKeys" default-expand-all />
        <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
    </div>
</template>

<script setup name="AllocateACL">
import { ref, onMounted } from 'vue';
import { list } from '@/api/menu'
import { ElMessage } from 'element-plus';
import { roleAllocMenu, roleLoadMenu } from '@/api/role';

const props = defineProps(['id'])
const emit = defineEmits(['allocateSuccess'])

const defaultProps = {
    children: 'children',
    label: 'name',
}

const tree = ref()
const loading = ref(false)
const formLoading = ref(false)
let records = ref([])
const defaultCheckedKeys = ref([])

onMounted(() => {
    loadMenuTree()
})

const loadMenuTree = async () => {
    formLoading.value = true
    await loadMenu()
    await loadMenuByRole()
    formLoading.value = false
}

const loadMenu = async () => {
    const data = await list();
    records.value = data.data
}

const loadMenuByRole = async () => {
    const data = await roleLoadMenu(props.id)
    tree.value.setCheckedKeys(data.data)
}

const submit = async () => {
    try {
        const checkedKeys = tree.value.getCheckedKeys();
        const halfCheckedKeys = tree.value.getHalfCheckedKeys();
        const roleAllocMenuRequest = { id: props.id, menuIdList: [...checkedKeys, ...halfCheckedKeys] }
        const data = await roleAllocMenu(roleAllocMenuRequest)
        if (data.code === 200) {
            ElMessage.success('分配成功')
            emit('allocateSuccess')
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped lang="scss"></style>
